package com.longli.tank;

import java.awt.*;

public class Bullet extends AbstractGameObject{
    private int x,y;
    private Dir dir;
    private Group group;
    private static final  int SPEED=10;
    private boolean live=true;
    private Rectangle rect;
    private int w=ResourceMgr.bulletU.getWidth();
    private int h=ResourceMgr.bulletU.getHeight();

    public Bullet(int x, int y, Dir dir,Group group) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.group=group;
        rect=new Rectangle(x,y,w,h);
    }

    @Override
    public boolean isLive() {
        return live;
    }

    public void setLive(boolean live) {
        this.live = live;
    }

    @Override
    public void paint(Graphics g){
        //if(this.group==Group.BAD){
            switch (dir){
                case L:
                    g.drawImage(ResourceMgr.bulletL,x,y,null);
                    break;
                case R:
                    g.drawImage(ResourceMgr.bulletR,x,y,null);
                    break;
                case U:
                    g.drawImage(ResourceMgr.bulletU,x,y,null);
                    break;
                case D:
                    g.drawImage(ResourceMgr.bulletD,x,y,null);
                    break;
            //}
        }
        move();
        //update rect
        rect.x=x;
        rect.y=y;
    }

    private void move() {
        switch (dir){
            case L:
                x-=SPEED;
                break;
            case R:
                x+=SPEED;
                break;
            case U:
                y-=SPEED;
                break;
            case D:
                y+=SPEED;
                break;
        }
        boundCheck();
    }

    public void collidesWithTank(Tank tank) {
        if(this.group==tank.getGroup()){
            return;
        }
        if(!tank.isLive()||!tank.isLive()){
            return;
        }
        //Rectangle rect=new Rectangle(x,y,ResourceMgr.bulletU.getWidth(),ResourceMgr.bulletU.getHeight());
        Rectangle recTank=new Rectangle(tank.getX(),tank.getY(),ResourceMgr.goodTankU.getWidth(),ResourceMgr.goodTankU.getHeight());
        if(rect.intersects(recTank)){
            this.die();
            tank.die();
        }
    }

    public Rectangle getRect(){
        return rect;
    }

    private void boundCheck() {
        if(x<0||y<30||x>TankFrame.INSTANCE.GAME_WIDTH||y>TankFrame.INSTANCE.GAME_HEIGHT){
            live=false;
        }
    }

    public void die(){
        this.setLive(false);
    }


    @Override
    public String toString() {
        return "Bullet{" +
                "x=" + x +
                ", y=" + y +
                ", dir=" + dir +
                ", group=" + group +
                ", live=" + live +
                ", rect=" + rect +
                ", w=" + w +
                ", h=" + h +
                '}';
    }
}
